package me.zhengjie.timing.plc;

import lombok.RequiredArgsConstructor;
import me.zhengjie.WcsReport.WcsReportService;
import me.zhengjie.agvSend.AgvSendService;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.entity.*;
import me.zhengjie.pojo.vo.AgvTaskSubmitVo;
import me.zhengjie.pojo.vo.TestVo;
import me.zhengjie.sqlservice.*;
import me.zhengjie.tcp.FluentFrame;
import me.zhengjie.utility.IdWorker;
import me.zhengjie.utility.liftState.PriorityEnum;
import me.zhengjie.utility.state.MaterialStatus;
import me.zhengjie.utility.state.TaskStatus;
import me.zhengjie.utility.state.TaskType;
import net.dreamlu.mica.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class FluentFrameTimingA {
    private static final Logger fluentFrameLog = LoggerFactory.getLogger("fluentFrame");

    private final WcsFluentFrameConfigService wcsFluentFrameConfigService;

    private final FluentFrame fluentFrame;

//    private final fluentFrame fluentFrame;
//
//    private final FluentFrameTCPB fluentFrameTCPB;

    private final WcsReportService wcsReportService;

    private final WcsInboundMissionService wcsInboundMissionService;

    private final AgvSendService agvSendService;

    private final WcsOutboundMissionService wcsOutboundMissionService;

    private final IdWorker idWorker;

    private final WcsFluentFrameOutboundDetailsService wcsFluentFrameOutboundDetailsService;

    private final WcsFluentFrameOutboundDetailsHistoryService wcsFluentFrameOutboundDetailsHistoryService;

    private final NestingMiddleTableService nestingMiddleTableService;

    private final WcsAgvReleaseGoodsService wcsAgvReleaseGoodsService;

    private final WcsConfigurationService wcsConfigurationService;

    private final WcsFluentFrameNgService wcsFluentFrameNgService;

    //    @Transactional
    @Scheduled(fixedDelay = 1000)
    public void fluentFrame() {
        List<WcsOutboundMission> wcsOutboundMissions = wcsOutboundMissionService.selectTask(TaskStatus.Task_create.getStatus(), TaskType.WORKBIN.getStatus());
        fluentFrameLog.info("流利架查询出库任务数据：{}", wcsOutboundMissions);
        Set<String> wcsOutboundMissionSet = wcsOutboundMissions.stream().map(WcsOutboundMission::getDestination).collect(Collectors.toSet());
        if (!wcsOutboundMissionSet.isEmpty()) {
            for (String destination : wcsOutboundMissionSet) {
                //出库任务终点工位
//            String destination = wcsOutboundMission.getDestination();
                //根据出库任务工位查询，查询对应流利架、
                List<WcsFluentFrameConfig> wcsFluentFrameConfigList = wcsFluentFrameConfigService.selectStorageRegion(destination);
                int totalSize = wcsFluentFrameConfigList.stream()
                        .mapToInt(config -> config.getSize() != null ? config.getSize() : 0)
                        .sum();

                List<WcsOutboundMission> wcsOutboundMissions1 = wcsOutboundMissionService.selectStatusAndDestinationAndContainerType(TaskStatus.Task_create.getStatus(), destination, TaskType.WORKBIN.getStatus());
                int time = 0;
                if (!wcsOutboundMissions1.isEmpty()) {
                    WcsOutboundMission wcsOutboundMission = wcsOutboundMissions1.get(0);
                    LocalDateTime createTime = wcsOutboundMission.getCreateTime();
                    LocalDateTime now = LocalDateTime.now();
                    time = (int) Duration.between(createTime, now).getSeconds();
                }
                //2F出库时间
                WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_OUTBOUND_TIME.getMessage());
                int outTime = 0;
                if (wcsConfiguration != null) {
                    outTime = Integer.parseInt(wcsConfiguration.getConfigValue());
                }
                if (totalSize <= 2) {
                    if (!wcsFluentFrameConfigList.isEmpty() && !wcsOutboundMissions1.isEmpty()) {
                        for (WcsOutboundMission wcsOutboundMission : wcsOutboundMissions1) {
                            List<WcsFluentFrameConfig> wcsFluentFrameConfigs = wcsFluentFrameConfigService.selectStorageRegion(destination);
                            WcsFluentFrameConfig wcsFluentFrameConfig = wcsFluentFrameConfigs.stream()
                                    .sorted(Comparator.comparingInt(WcsFluentFrameConfig::getSize)   // 1. 最小 size
                                            .thenComparing(c -> !"left".equals(c.getDirection()))) // 2. left 优先
                                    .findFirst()     // 3. 拿第一个
                                    .orElse(null);
                            if (wcsFluentFrameConfig != null) {
                                Integer size = wcsFluentFrameConfig.getSize();
                                String outStorageCode = wcsFluentFrameConfig.getOutStorageCode();
                                String sortingStorage = wcsFluentFrameConfig.getSortingStorage();
                                Integer wcsFluentFrameConfigId = wcsFluentFrameConfig.getId();
                                if (size < 3) {
                                    String outboundCode = wcsOutboundMission.getOutboundCode();
                                    String outContainerCode = wcsOutboundMission.getContainerCode();
                                    AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                    //todo 任务类型，根据现场情况来定
                                    agvTaskSubmitDto.setTaskType("BBBBBB");
                                    ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                    TargetRoute targetRoute = new TargetRoute();
                                    TargetRoute targetRoutes = new TargetRoute();
                                    //添加起点
                                    targetRoute.setSeq(0);
                                    targetRoute.setType(TaskType.STORAGE.getMessage());
                                    targetRoute.setCode(wcsOutboundMission.getSource());
                                    //添加终点
                                    targetRoutes.setSeq(1);
                                    targetRoutes.setType(TaskType.STORAGE.getMessage());
                                    targetRoutes.setCode(outStorageCode);
                                    targetRouteList.add(targetRoute);
                                    targetRouteList.add(targetRoutes);
                                    agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                    agvTaskSubmitDto.setRobotTaskCode(outboundCode);
                                    agvTaskSubmitDto.setInitPriority(wcsOutboundMission.getPriority());

                                    CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
                                    carrierInfoDto.setCarrierCode(outContainerCode);
                                    carrierInfoDto.setCarrierType(TaskType.TWO_Task_assignment_Container_binding.getMessage());
                                    ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
                                    carrierInfoDtos.add(carrierInfoDto);
                                    ExtraDto extraDto = new ExtraDto();
                                    extraDto.setCarrierInfo(carrierInfoDtos);
                                    agvTaskSubmitDto.setExtra(extraDto);
                                    String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                    if (taskCode != null) {
//                                    if (true) {
//                                        fluentFrame.writeWithRetry(threeReturnResult, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        //记录agv放货表
                                        WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
                                        wcsAgvReleaseGoods.setTaskCode(outboundCode);
                                        wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
                                        wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
                                        wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_ANTI_CARGO.getStatus());
                                        wcsAgvReleaseGoods.setFloor(TaskType.TWO_FLOOR.getStatus());
                                        boolean b2 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
                                        if (!b2) {
                                            fluentFrameLog.error("琉璃架出库，添加到放货表失败");
                                            continue;
                                        }
                                        //记录载具出库位置到哪个流利架
                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = new WcsFluentFrameOutboundDetails();
                                        wcsFluentFrameOutboundDetails.setContainerCode(outContainerCode);
                                        wcsFluentFrameOutboundDetails.setStorageCode(sortingStorage);
                                        wcsFluentFrameOutboundDetails.setIsNest(0);
                                        wcsFluentFrameOutboundDetails.setAgvPlace(0);
                                        wcsFluentFrameOutboundDetails.setUpdateTime(LocalDateTime.now());
                                        wcsFluentFrameOutboundDetailsService.insertFluentFrameOutboundDetails(wcsFluentFrameOutboundDetails);
                                        size++;
                                        //修改流利架数量
                                        fluentFrameLog.info("修改琉璃架数量{},{}", wcsFluentFrameConfigId, size);
                                        wcsFluentFrameConfigService.updateSize(wcsFluentFrameConfigId, size);
                                        //修改任务状态已发送
                                        boolean b = wcsOutboundMissionService.updateMissionStatusFluentFrameStorage(outboundCode, TaskStatus.task_send.getStatus(), outStorageCode);
                                        if (!b) {
                                            fluentFrameLog.error("出库下发任务，修改数据库失败");
                                            throw new RuntimeException("出库下发任务，修改数据库失败");
                                        }
                                    }
                                }
                            }
                        }

//                        for (WcsFluentFrameConfig wcsFluentFrameConfig : wcsFluentFrameConfigList) {
//                            fluentFrameLog.info("查询到流利架配置：{}", wcsFluentFrameConfig);
//                            String outStorageCode = wcsFluentFrameConfig.getOutStorageCode();
//                            Integer wcsFluentFrameConfigId = wcsFluentFrameConfig.getId();
//                            Integer size = wcsFluentFrameConfig.getSize();
//
//                            String sortingStorage = wcsFluentFrameConfig.getSortingStorage();
//                            Integer storageSize = 3;
//                            storageSize = storageSize - size;
//                            //查询2楼料箱状态为0的入库任务到该储位
//                            if (storageSize > 0) {
//                                List<WcsOutboundMission> wcsOutboundMissionList = wcsOutboundMissionService.selectStatusAndDestinationAndContainerTypePage(TaskStatus.Task_create.getStatus(), destination, TaskType.WORKBIN.getStatus(), storageSize);
//                                if (!wcsOutboundMissionList.isEmpty()) {
//                                    //下发agv任务，修改状态为1
//                                    for (WcsOutboundMission outboundMission : wcsOutboundMissionList) {
//                                        String outboundCode = outboundMission.getOutboundCode();
//                                        String outContainerCode = outboundMission.getContainerCode();
//                                        //琉璃架修改出库表记录当前出库所在储位
////                                    boolean b1 = wcsOutboundMissionService.updateDestination(id, outStorageCode);
////                                    if (!b1) {
////                                        fluentFrame.error("修改二楼琉璃架出库终点异常");
////                                        throw new RuntimeException("修改二楼琉璃架出库终点异常");
////                                    }
//                                        AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
//                                        //todo 任务类型，根据现场情况来定
//                                        agvTaskSubmitDto.setTaskType("BBBBBB");
//                                        ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
//                                        TargetRoute targetRoute = new TargetRoute();
//                                        TargetRoute targetRoutes = new TargetRoute();
//                                        //添加起点
//                                        targetRoute.setSeq(0);
//                                        targetRoute.setType(TaskType.STORAGE.getMessage());
//                                        targetRoute.setCode(outboundMission.getSource());
//                                        //添加终点
//                                        targetRoutes.setSeq(1);
//                                        targetRoutes.setType(TaskType.STORAGE.getMessage());
//                                        targetRoutes.setCode(outStorageCode);
//                                        targetRouteList.add(targetRoute);
//                                        targetRouteList.add(targetRoutes);
//                                        agvTaskSubmitDto.setTargetRoute(targetRouteList);
//                                        agvTaskSubmitDto.setRobotTaskCode(outboundCode);
//                                        agvTaskSubmitDto.setInitPriority(outboundMission.getPriority());
//                                        String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
//                                        if (taskCode != null) {
////                                        fluentFrame.writeWithRetry(threeReturnResult, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
//                                            //记录agv放货表
//                                            WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
//                                            wcsAgvReleaseGoods.setTaskCode(outboundCode);
//                                            wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
//                                            wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
//                                            wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_ANTI_CARGO.getStatus());
//                                            wcsAgvReleaseGoods.setFloor(TaskType.TWO_FLOOR.getStatus());
//                                            boolean b2 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
//                                            if (!b2) {
//                                                fluentFrameLog.error("琉璃架出库，添加到放货表失败");
//                                                continue;
//                                            }
//                                            //记录载具出库位置到哪个流利架
//                                            WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = new WcsFluentFrameOutboundDetails();
//                                            wcsFluentFrameOutboundDetails.setContainerCode(outContainerCode);
//                                            wcsFluentFrameOutboundDetails.setStorageCode(sortingStorage);
//                                            wcsFluentFrameOutboundDetails.setIsNest(0);
//                                            wcsFluentFrameOutboundDetails.setAgvPlace(0);
//                                            wcsFluentFrameOutboundDetails.setUpdateTime(LocalDateTime.now());
//                                            wcsFluentFrameOutboundDetailsService.insertFluentFrameOutboundDetails(wcsFluentFrameOutboundDetails);
//                                            size++;
//                                            //修改流利架数量
//                                            wcsFluentFrameConfigService.updateSize(wcsFluentFrameConfigId, size);
//                                            //修改任务状态已发送
//                                            boolean b = wcsOutboundMissionService.updateMissionStatusFluentFrameStorage(outboundCode, TaskStatus.task_send.getStatus(), outStorageCode);
//                                            if (!b) {
//                                                fluentFrameLog.error("出库下发任务，修改数据库失败");
//                                                throw new RuntimeException("出库下发任务，修改数据库失败");
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                        }
                    }
                } else if (time > outTime) {
                    if (!wcsFluentFrameConfigList.isEmpty() && !wcsOutboundMissions1.isEmpty()) {
                        for (WcsOutboundMission wcsOutboundMission : wcsOutboundMissions1) {
                            List<WcsFluentFrameConfig> wcsFluentFrameConfigs = wcsFluentFrameConfigService.selectStorageRegion(destination);
                            WcsFluentFrameConfig wcsFluentFrameConfig = wcsFluentFrameConfigs.stream()
                                    .sorted(Comparator.comparingInt(WcsFluentFrameConfig::getSize)   // 1. 最小 size
                                            .thenComparing(c -> !"left".equals(c.getDirection()))) // 2. left 优先
                                    .findFirst()     // 3. 拿第一个
                                    .orElse(null);
                            fluentFrameLog.info("查询数量最小的值：{}", wcsFluentFrameConfig);
                            if (wcsFluentFrameConfig != null) {
                                Integer size = wcsFluentFrameConfig.getSize();
                                String outStorageCode = wcsFluentFrameConfig.getOutStorageCode();
                                String sortingStorage = wcsFluentFrameConfig.getSortingStorage();
                                Integer wcsFluentFrameConfigId = wcsFluentFrameConfig.getId();
                                if (size < 3) {
                                    String outboundCode = wcsOutboundMission.getOutboundCode();
                                    String outContainerCode = wcsOutboundMission.getContainerCode();
                                    AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                    //todo 任务类型，根据现场情况来定
                                    agvTaskSubmitDto.setTaskType("BBBBBB");
                                    ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                    TargetRoute targetRoute = new TargetRoute();
                                    TargetRoute targetRoutes = new TargetRoute();
                                    //添加起点
                                    targetRoute.setSeq(0);
                                    targetRoute.setType(TaskType.STORAGE.getMessage());
                                    targetRoute.setCode(wcsOutboundMission.getSource());
                                    //添加终点
                                    targetRoutes.setSeq(1);
                                    targetRoutes.setType(TaskType.STORAGE.getMessage());
                                    targetRoutes.setCode(outStorageCode);
                                    targetRouteList.add(targetRoute);
                                    targetRouteList.add(targetRoutes);
                                    agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                    agvTaskSubmitDto.setRobotTaskCode(outboundCode);
                                    agvTaskSubmitDto.setInitPriority(wcsOutboundMission.getPriority());

                                    CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
                                    carrierInfoDto.setCarrierCode(outContainerCode);
                                    carrierInfoDto.setCarrierType(TaskType.TWO_Task_assignment_Container_binding.getMessage());
                                    ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
                                    carrierInfoDtos.add(carrierInfoDto);
                                    ExtraDto extraDto = new ExtraDto();
                                    extraDto.setCarrierInfo(carrierInfoDtos);
                                    agvTaskSubmitDto.setExtra(extraDto);
                                    String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                    if (taskCode != null) {
//                                        fluentFrame.writeWithRetry(threeReturnResult, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        //记录agv放货表
                                        WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
                                        wcsAgvReleaseGoods.setTaskCode(outboundCode);
                                        wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
                                        wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
                                        wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_ANTI_CARGO.getStatus());
                                        wcsAgvReleaseGoods.setFloor(TaskType.TWO_FLOOR.getStatus());
                                        boolean b2 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
                                        if (!b2) {
                                            fluentFrameLog.error("琉璃架出库，添加到放货表失败");
                                            continue;
                                        }
                                        //记录载具出库位置到哪个流利架
                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = new WcsFluentFrameOutboundDetails();
                                        wcsFluentFrameOutboundDetails.setContainerCode(outContainerCode);
                                        wcsFluentFrameOutboundDetails.setStorageCode(sortingStorage);
                                        wcsFluentFrameOutboundDetails.setIsNest(0);
                                        wcsFluentFrameOutboundDetails.setAgvPlace(0);
                                        wcsFluentFrameOutboundDetails.setUpdateTime(LocalDateTime.now());
                                        wcsFluentFrameOutboundDetailsService.insertFluentFrameOutboundDetails(wcsFluentFrameOutboundDetails);
                                        size++;
                                        //修改流利架数量
                                        wcsFluentFrameConfigService.updateSize(wcsFluentFrameConfigId, size);
                                        //修改任务状态已发送
                                        boolean b = wcsOutboundMissionService.updateMissionStatusFluentFrameStorage(outboundCode, TaskStatus.task_send.getStatus(), outStorageCode);
                                        if (!b) {
                                            fluentFrameLog.error("出库下发任务，修改数据库失败");
                                            throw new RuntimeException("出库下发任务，修改数据库失败");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //

        //查询所有流利架
        List<WcsFluentFrameConfig> wcsFluentFrameConfigList = wcsFluentFrameConfigService.selectAll();
        if (!wcsFluentFrameConfigList.isEmpty()) {
            for (WcsFluentFrameConfig wcsFluentFrameConfig : wcsFluentFrameConfigList) {
                Integer singleOrDouble = wcsFluentFrameConfig.getSingleOrDouble();
                Integer size = wcsFluentFrameConfig.getSize();
                if (singleOrDouble == 2) {
                    fluentFrameLog.info("气缸对接水平，查询流利架数据：{}", wcsFluentFrameConfig);
                    //双层流利架
                    //查询气缸地址位，当前状态
                    Integer id = wcsFluentFrameConfig.getId();
//                    Integer cylinder = wcsFluentFrameConfig.getCylinder();
                    String region = wcsFluentFrameConfig.getRegion();
                    Integer unitId = wcsFluentFrameConfig.getUnitId();
                    Integer sortingAddress = wcsFluentFrameConfig.getSortingAddress();
                    Integer sortingResultAddress = wcsFluentFrameConfig.getSortingResultAddress();
                    Integer mode = wcsFluentFrameConfig.getMode();
                    String storageRegion = wcsFluentFrameConfig.getStorageRegion();
                    String storageCode = wcsFluentFrameConfig.getOutStorageCode();
                    String sortingContainerCode = wcsFluentFrameConfig.getSortingContainerCode();
                    Integer threeInbReturnResult = wcsFluentFrameConfig.getThreeInbReturnResult();
                    Integer writePlc = wcsFluentFrameConfig.getWritePlc();
                    Integer sortingReadingFinish = wcsFluentFrameConfig.getSortingReadingFinish();
                    String inboundStorageCode = wcsFluentFrameConfig.getInboundStorageCode();
                    Integer cylinderControlAddress = wcsFluentFrameConfig.getCylinderControlAddress();
                    Integer returnToWarehouse = wcsFluentFrameConfig.getReturnToWarehouse();
                    Integer returnReading = wcsFluentFrameConfig.getReturnReading();
                    Integer returnReadingCode = wcsFluentFrameConfig.getReturnReadingCode();
                    Integer sortingReadAddress = wcsFluentFrameConfig.getSortingReadAddress();
                    Integer inboundThreeAddress = wcsFluentFrameConfig.getInboundThreeAddress();
                    Integer inboundTwoAddress = wcsFluentFrameConfig.getInboundTwoAddress();
                    Integer inboundOneAddress = wcsFluentFrameConfig.getInboundOneAddress();
                    String direction = wcsFluentFrameConfig.getDirection();
                    String workstation = wcsFluentFrameConfig.getWorkstation();
                    Integer inbRequestTake = wcsFluentFrameConfig.getInbRequestTake();
                    Integer inbPlcStatus = wcsFluentFrameConfig.getInbPlcStatus();
                    Integer outRequestRelease = wcsFluentFrameConfig.getOutRequestRelease();
                    String sweepStorage = wcsFluentFrameConfig.getSweepStorage();
                    String deviceIp = wcsFluentFrameConfig.getDeviceIp();
                    Integer fluentFrameAMove = fluentFrame.readHoldingRegisters(region, 1, 1);
                    if (fluentFrameAMove != null && fluentFrameAMove == 2) {
                        //分拣回库判断PLC请求往前流
                        Integer returnToWarehouseStatus = fluentFrame.readHoldingRegisters(region, returnToWarehouse, unitId);
                        fluentFrameLog.info("回库PLC请求往前流：{}", returnToWarehouseStatus);
                        if (returnToWarehouseStatus != null && returnToWarehouseStatus == 1) {
                            //请求往前流，判断二次读码信息是否一致
                            Integer readHoldingRegisters = fluentFrame.readHoldingRegisters(region, returnReading, unitId);
                            Integer sortingReadingFinishStatus = fluentFrame.readHoldingRegisters(region, sortingReadingFinish, unitId);
                            if (readHoldingRegisters == 1 && sortingReadingFinishStatus == 1) {
                                String returnBox = fluentFrame.readHoldingRegistersString(region, returnReadingCode, unitId);//出库读码地址位
                                String inbBox = fluentFrame.readHoldingRegistersString(region, sortingReadAddress, unitId);//回库扫码地址位
                                fluentFrameLog.info("回库,出库读码：{}，回库读码{}", returnBox, inbBox);
                                //记录流利架回库箱号
                                WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails1 = wcsFluentFrameOutboundDetailsService.selectContainerCode(returnBox);
                                if (wcsFluentFrameOutboundDetails1 != null) {
                                    //走回库
                                    wcsFluentFrameConfigService.updateSortingContainerCode(id, returnBox);
                                    if (returnBox.equals(inbBox)) {
                                        //读码一致判断中间是否存在
                                        List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(inbBox);
                                        if (!nestingMiddleTables.isEmpty()) {
                                            //判断物料信息是否一致。一致
                                            TestVo testVo = wcsReportService.wmsInventoryInformation(inbBox);
                                            Integer code = testVo.getCode();
                                            if (code != 200) {
                                                //PLC报警WMS未找到载具码信息
                                                fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(returnBox, MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getMessage());
                                                if (wcsFluentFrameNgs.isEmpty()) {
                                                    WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                    wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getMessage());
                                                    wcsFluentFrameNg.setContainerCode(returnBox);
                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                    boolean b = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                } else {
                                                    //更新最新问题时间
                                                    WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                    wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                }
//                                            boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                            } else {
                                                //对比库存信息 对比物料条码和数量
                                                List<MaterialDao> materialDaoList = testVo.getData();
                                                HashSet<InventoryContrast> mesInventorySet = new HashSet<>();
                                                HashSet<InventoryContrast> wmsInventorySet = new HashSet<>();
                                                for (MaterialDao datum : materialDaoList) {
                                                    InventoryContrast wmsInventory = new InventoryContrast();
                                                    BeanUtils.copyProperties(datum, wmsInventory);
                                                    wmsInventorySet.add(wmsInventory);
                                                }
                                                for (NestingMiddleTable middleTable : nestingMiddleTables) {
                                                    InventoryContrast wmsInventory = new InventoryContrast();
                                                    BeanUtils.copyProperties(middleTable, wmsInventory);
                                                    mesInventorySet.add(wmsInventory);
                                                }
                                                fluentFrameLog.info("回库对比库存信息：MES{},WMS:{}", mesInventorySet, wmsInventorySet);
                                                if (!mesInventorySet.equals(wmsInventorySet)) {
                                                    fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                    List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(returnBox, MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getMessage());
                                                    if (wcsFluentFrameNgs.isEmpty()) {
                                                        //WMS和WES库存信息不一致
                                                        WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                        wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getMessage());
                                                        wcsFluentFrameNg.setContainerCode(returnBox);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        boolean b = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                    } else {
                                                        WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                    }
//                                                boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                } else {
                                                    //创建入库任务
                                                    InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                                    inboundStorageApplyDto.setContainerCode(inbBox);
                                                    //查询入库明细表，是否回库
//                                                            WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                                    inboundStorageApplyDto.setNest(true);
                                                    inboundStorageApplyDto.setFloor(TaskType.TWO_FLOOR.getMessage());
//                                            List<NestingMiddleTable> nestingMiddleTables1 = nestingMiddleTableService.selectContainerCode(palletCode);
                                                    ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
                                                    for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables) {
                                                        NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
                                                        BeanUtils.copyProperties(nestingMiddleTable, nestingMiddleTable1);
                                                        materialDaos.add(nestingMiddleTable1);
                                                    }
                                                    inboundStorageApplyDto.setData(materialDaos);
                                                    String destinationStorageCode = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                                    if (destinationStorageCode != null) {
                                                        String nestingJson = JsonUtil.toJson(materialDaos);
                                                        WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                        wcsInboundMission.setIsNest(0);
                                                        wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                        //生成入库任务
                                                        wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                        wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                        wcsInboundMission.setContainerCode(inbBox);
                                                        wcsInboundMission.setSource(inboundStorageCode);
                                                        wcsInboundMission.setDestination(destinationStorageCode);
                                                        wcsInboundMission.setContainerType(TaskType.WORKBIN.getStatus());
                                                        wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                        wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                                        wcsInboundMission.setFloor(TaskType.TWO_FLOOR.getMessage());

                                                        wcsInboundMission.setPriority(90);
                                                        StringBuilder sb = new StringBuilder();
                                                        List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                                                        for (String materialCode : materialCodeList) {
                                                            if (sb.length() > 0) {
                                                                sb.append(",");
                                                            }
                                                            sb.append(materialCode);
                                                        }
                                                        wcsInboundMission.setIsPlc(1);
                                                        wcsInboundMission.setIsWms(1);
                                                        wcsInboundMission.setNestingJson(nestingJson);

                                                        boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                        //todo 更新A区时间，cv需要改其他区域
//                                                    WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.FLUENT_FRAME_A.getMessage());
//                                                    if (wcsConfiguration != null) {
//                                                        String configKey = wcsConfiguration.getConfigKey();
//                                                        LocalDateTime updateTime = LocalDateTime.now();
//                                                        wcsConfigurationService.updateValue(configKey, String.valueOf(updateTime));
//                                                    }
                                                        if (!b2) {
                                                            fluentFrameLog.error("创建空箱入库任务失败");
                                                            throw new RuntimeException("创建空箱入库任务失败");
                                                        }
                                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(returnBox);
                                                        if (wcsFluentFrameOutboundDetails != null) {
                                                            WcsFluentFrameOutboundDetailsHistory wcsFluentFrameOutboundDetailsHistory = new WcsFluentFrameOutboundDetailsHistory();
                                                            BeanUtils.copyProperties(wcsFluentFrameOutboundDetails, wcsFluentFrameOutboundDetailsHistory);
                                                            wcsFluentFrameOutboundDetailsHistoryService.insertFluentFrameOutboundDetailsHistory(wcsFluentFrameOutboundDetailsHistory);
                                                            //删除琉璃架出库明细
                                                            boolean b = wcsFluentFrameOutboundDetailsService.deleteContainerCode(returnBox);
                                                        }
                                                        //通知琉璃架往前流
                                                        fluentFrameLog.info("通知PLC往前流数据：{}", 1);
                                                        fluentFrame.writeWithRetry(sortingResultAddress, 1, unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                    }
                                                }
                                            }
                                        } else {
                                            //中间表不存在，判断一分钟后还不存在报警
                                            WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(inbBox);
                                            if (wcsFluentFrameOutboundDetails != null) {
                                                LocalDateTime updateTime = wcsFluentFrameOutboundDetails.getUpdateTime();
                                                LocalDateTime now = LocalDateTime.now();
                                                long seconds = Duration.between(updateTime, now).getSeconds();
                                                if (seconds > 60) {
                                                    boolean b = fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);//通知PLC报警
                                                    List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(returnBox, MaterialStatus.RETURN_ONE_RESULT_NO.getMessage());
                                                    if (wcsFluentFrameNgs.isEmpty()) {
                                                        //返回PLC，报警
                                                        WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                        wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_NO.getMessage());
                                                        wcsFluentFrameNg.setContainerCode(returnBox);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                    } else {
                                                        WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        boolean b = fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.TWO_SIDES_CODE_MISMATCH.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);//通知PLC报警
                                        List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(returnBox, MaterialStatus.TWO_SIDES_CODE_MISMATCH.getMessage());
                                        if (wcsFluentFrameNgs.isEmpty()) {
                                            //读码不一致直接报警
                                            WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                            wcsFluentFrameNg.setNg(MaterialStatus.TWO_SIDES_CODE_MISMATCH.getMessage());
                                            wcsFluentFrameNg.setContainerCode(returnBox);
                                            wcsFluentFrameNg.setIp(deviceIp);
                                            boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                        } else {
                                            WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                            wcsFluentFrameNg.setIp(deviceIp);
                                            wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                        }
                                    }
                                }
                            }
                        }


                        Integer sortingStatus = fluentFrame.readHoldingRegisters(region, sortingAddress, unitId);
                        Integer readHoldingRegisters = fluentFrame.readHoldingRegisters(region, sortingReadingFinish, unitId);
                        fluentFrameLog.info("读取分解地址位结果：{}，读码是否完成：{}", sortingStatus, readHoldingRegisters);
                        //判断气缸当前状态,入库
                        if (sortingStatus != null && sortingStatus == 1 && readHoldingRegisters == 1) {
                            fluentFrameLog.info("分拣读码信息地址位有货:{},读码地址位有货信息：{}", sortingAddress, sortingStatus);
                            //分拣区有货，获取读码结果
                            String palletCode = fluentFrame.readHoldingRegistersString(region, sortingReadAddress, unitId);
                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCodeNotTask(palletCode);
                            if (wcsInboundMissionList.isEmpty()){
                                WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails1 = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                fluentFrameLog.info("分拣区读码地址位:{},分拣区读码信息：{},查询出库明细是否需要回库:{}", sortingReadAddress, palletCode, wcsFluentFrameOutboundDetails1);
                                if (writePlc == 0 && wcsFluentFrameOutboundDetails1 == null) {
                                    fluentFrameLog.info("入库查询二边读码是否一直：PLC{}，WCS:{}",palletCode,sweepStorage);
                                    if (palletCode.equals(sweepStorage)) {
                                        //是空箱入库还是正常入库
                                        if (mode == 0) {
                                            //空箱入库
                                            //查詢嵌套信息不能存在该物料
                                            List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(palletCode);
                                            if (!nestingMiddleTables.isEmpty()) {
                                                fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_NG.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_NG.getMessage());
                                                if (wcsFluentFrameNgs.isEmpty()) {
//                                            boolean b = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                    WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                    wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_NG.getMessage());
                                                    wcsFluentFrameNg.setContainerCode(palletCode);
                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                    boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                } else {
                                                    WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                    wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                }
                                            } else {
                                                InboundIsCodeExistDto inboundIsCodeExist = new InboundIsCodeExistDto();
                                                inboundIsCodeExist.setContainerCode(palletCode);
                                                inboundIsCodeExist.setNest(false);
                                                inboundIsCodeExist.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExist);
                                                if (b) {
                                                    fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                    List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getMessage());
                                                    if (wcsFluentFrameNgs.isEmpty()) {
//                                                boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                        WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                        wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getMessage());
                                                        wcsFluentFrameNg.setContainerCode(palletCode);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                    } else {
                                                        WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                    }
                                                } else {
                                                    //向WMS下发空箱入库申请储位
//                                        ReturnVo returnVo1 = wcsReportService.emptyContainer(storageRegion);
                                                    InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                                    inboundStorageApplyDto.setContainerCode(palletCode);
                                                    inboundStorageApplyDto.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                    inboundStorageApplyDto.setNest(false);
                                                    inboundStorageApplyDto.setData(null);
//                                                inboundStorageApplyDto.setData(null);
                                                    String destinatin = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                                    if (destinatin != null) {
                                                        //todo 更新A区时间，cv需要改其他区域
//                                                    WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.FLUENT_FRAME_A.getMessage());
//                                                    if (wcsConfiguration != null) {
//                                                        String configKey = wcsConfiguration.getConfigKey();
//                                                        LocalDateTime updateTime = LocalDateTime.now();
//                                                        wcsConfigurationService.updateValue(configKey, String.valueOf(updateTime));
//                                                    }
                                                        //往plc写入ok
                                                        boolean b2 = fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                        if (b2) {
                                                            //查询NG，有就删除
                                                            List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCode(palletCode);
                                                            if (!wcsFluentFrameNgs.isEmpty()) {
                                                                for (WcsFluentFrameNg wcsFluentFrameNg : wcsFluentFrameNgs) {
                                                                    String containerCode = wcsFluentFrameNg.getContainerCode();
                                                                    wcsFluentFrameNgService.delectContainerCode(containerCode);
                                                                }
                                                            }
                                                            //生成入库任务
                                                            WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                            wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                            wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                            wcsInboundMission.setContainerCode(palletCode);
                                                            wcsInboundMission.setSource(inboundStorageCode);
                                                            wcsInboundMission.setDestination(destinatin);
                                                            wcsInboundMission.setContainerType(TaskType.EMPTY_MATERIAL_BOX_STORAGE.getStatus());
                                                            wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                            wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                                            wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                            wcsInboundMission.setPriority(90);
                                                            wcsInboundMission.setIsNest(0);
                                                            wcsInboundMission.setIsPlc(1);
                                                            wcsInboundMission.setIsWms(1);
                                                            wcsInboundMission.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                            boolean b1 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                            if (!b1) {
                                                                fluentFrameLog.error("创建空箱入库任务失败");
                                                                throw new RuntimeException("创建空箱入库任务失败");
                                                            }
                                                            //todo 1
//                                                        boolean b3 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                        }
                                                    } else {
                                                        fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                        List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getMessage());
                                                        if (wcsFluentFrameNgs.isEmpty()) {
//                                                    boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                            WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                            wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getMessage());
                                                            wcsFluentFrameNg.setContainerCode(palletCode);
                                                            wcsFluentFrameNg.setIp(deviceIp);
                                                            boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                        } else {
                                                            WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                            wcsFluentFrameNg.setIp(deviceIp);
                                                            wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                        }
                                                    }
                                                }

                                            }
                                        } else if (mode == 1) {
                                            WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                            fluentFrameLog.info("分拣区查询到出库任务:{}", wcsFluentFrameOutboundDetails);
                                            if (wcsFluentFrameOutboundDetails == null) {
                                                InboundIsCodeExistDto inboundIsCodeExist = new InboundIsCodeExistDto();
                                                inboundIsCodeExist.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                //1.发送wms查看栈板是否已入库
                                                inboundIsCodeExist.setContainerCode(palletCode);
                                                inboundIsCodeExist.setNest(false);
                                                boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExist);
                                                if (b) {
                                                    fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                    List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getMessage());
                                                    if (wcsFluentFrameNgs.isEmpty()) {
                                                        //                                                boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                        WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                        wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getMessage());
                                                        wcsFluentFrameNg.setContainerCode(palletCode);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                    } else {
                                                        WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                        wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                    }
                                                } else {
                                                    //2.查询嵌套信息是否嵌套
//                                        ReturnVo returnVo = wcsReportService.middleNestingData(palletCode);
                                                    List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(palletCode);
                                                    fluentFrameLog.info("双层流利架入库或回库，查询嵌套信息:{}", nestingMiddleTables);
                                                    if (nestingMiddleTables.isEmpty()) {
                                                        fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                        List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_NO.getMessage());
                                                        if (wcsFluentFrameNgs.isEmpty()) {
//                                                    boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                            WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                            wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_NO.getMessage());
                                                            wcsFluentFrameNg.setContainerCode(palletCode);
                                                            wcsFluentFrameNg.setIp(deviceIp);
                                                            boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                        } else {
                                                            WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                            wcsFluentFrameNg.setIp(deviceIp);
                                                            wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                        }
                                                    } else {
                                                        long rawMaterialsQ = nestingMiddleTables.stream().filter(f -> f.getMaterialCategory().equals(TaskType.MATERIAL_Q.getMessage())).count();
                                                        //判断是否自检
                                                        long rawMaterialsQQualified = nestingMiddleTables.stream().filter(f -> f.getMaterialCategory().equals(TaskType.MATERIAL_Q.getMessage()) && f.getSelfCheckStatus().equals("合格")).count();
                                                        //3.查询物料是否是原物料Q
                                                        fluentFrameLog.info("原物料Q数量：{},自检数量：{}", rawMaterialsQ, rawMaterialsQQualified);
                                                        if (rawMaterialsQ != 0) {
                                                            //判断是否自检
                                                            if (rawMaterialsQ == rawMaterialsQQualified) {
                                                                //向WMS申请终点储位
                                                                //todo　中间表查询栈板信息
                                                                InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                                                inboundStorageApplyDto.setContainerCode(palletCode);
                                                                //查询入库明细表，是否回库
//                                                            WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                                                inboundStorageApplyDto.setNest(false);
                                                                inboundStorageApplyDto.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                                List<NestingMiddleTable> nestingMiddleTables1 = nestingMiddleTableService.selectContainerCode(palletCode);
                                                                ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
                                                                for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables1) {
                                                                    NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
                                                                    BeanUtils.copyProperties(nestingMiddleTable, nestingMiddleTable1);
                                                                    materialDaos.add(nestingMiddleTable1);
                                                                }
                                                                inboundStorageApplyDto.setData(materialDaos);
                                                                fluentFrameLog.info("自检通过,申请入库：{}", inboundStorageApplyDto);
                                                                String destinationStorageCode = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                                                if (destinationStorageCode != null) {
                                                                    //库存一至
                                                                    boolean b3 = fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                                    if (b3) {
                                                                        //查询NG，有就删除
                                                                        List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCode(palletCode);
                                                                        if (!wcsFluentFrameNgs.isEmpty()) {
                                                                            for (WcsFluentFrameNg wcsFluentFrameNg : wcsFluentFrameNgs) {
                                                                                String containerCode = wcsFluentFrameNg.getContainerCode();
                                                                                wcsFluentFrameNgService.delectContainerCode(containerCode);
                                                                            }
                                                                        }
                                                                        String nestingJson = JsonUtil.toJson(materialDaos);
                                                                        WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                                        wcsInboundMission.setIsNest(0);
                                                                        wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                                        //生成入库任务
                                                                        wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                                        wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                                        wcsInboundMission.setContainerCode(palletCode);
                                                                        wcsInboundMission.setSource(inboundStorageCode);
                                                                        wcsInboundMission.setDestination(destinationStorageCode);
                                                                        wcsInboundMission.setContainerType(TaskType.WORKBIN.getStatus());
                                                                        wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                                        wcsInboundMission.setUpdateTime(LocalDateTime.now());

                                                                        wcsInboundMission.setPriority(90);
                                                                        StringBuilder sb = new StringBuilder();
                                                                        List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                                                                        for (String materialCode : materialCodeList) {
                                                                            if (sb.length() > 0) {
                                                                                sb.append(",");
                                                                            }
                                                                            sb.append(materialCode);
                                                                        }
                                                                        wcsInboundMission.setIsPlc(1);
                                                                        wcsInboundMission.setIsWms(1);
                                                                        wcsInboundMission.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                                        wcsInboundMission.setNestingJson(nestingJson);
                                                                        boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                                        if (!b2) {
                                                                            fluentFrameLog.error("创建空箱入库任务失败");
                                                                            throw new RuntimeException("创建空箱入库任务失败");
                                                                        }
                                                                        //todo 1
//                                                                    boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                                    }
                                                                } else {
                                                                    fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                                    List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getMessage());
                                                                    if (wcsFluentFrameNgs.isEmpty()) {
//                                                                boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                                        WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                                        wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getMessage());
                                                                        wcsFluentFrameNg.setContainerCode(palletCode);
                                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                                        boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                                    } else {
                                                                        WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                                        wcsFluentFrameNg.setIp(deviceIp);
                                                                        wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                                    }
                                                                }
                                                            } else {
                                                                //自检不通过
                                                                fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_QUALITY_TESTING_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                                List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_QUALITY_TESTING_NO.getMessage());
                                                                if (wcsFluentFrameNgs.isEmpty()) {
//                                                            boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                                    WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                                    wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_QUALITY_TESTING_NO.getMessage());
                                                                    wcsFluentFrameNg.setContainerCode(palletCode);
                                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                                    boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                                } else {
                                                                    WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                                    wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                                }
                                                            }
                                                        } else {
                                                            fluentFrameLog.info("不是原物料Q");
                                                            //向WMS申请终点储位
                                                            InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                                            inboundStorageApplyDto.setContainerCode(palletCode);
                                                            //查询入库明细表，是否回库
//                                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
//                                                            Integer isNest = wcsFluentFrameOutboundDetails.getIsNest();
                                                            inboundStorageApplyDto.setNest(false);
                                                            inboundStorageApplyDto.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                            List<NestingMiddleTable> nestingMiddleTables1 = nestingMiddleTableService.selectContainerCode(palletCode);
                                                            ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
                                                            for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables1) {
                                                                NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
                                                                BeanUtils.copyProperties(nestingMiddleTable, nestingMiddleTable1);
                                                                materialDaos.add(nestingMiddleTable1);
                                                            }
                                                            inboundStorageApplyDto.setData(materialDaos);
                                                            fluentFrameLog.info("不是原物料Q,入库请求储位参数：{}", inboundStorageApplyDto);
                                                            String destinationStorageCode = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                                            if (destinationStorageCode != null) {
                                                                //库存一至
                                                                boolean b2 = fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                                if (b2) {
                                                                    //查询NG，有就删除
                                                                    List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCode(palletCode);
                                                                    if (!wcsFluentFrameNgs.isEmpty()) {
                                                                        for (WcsFluentFrameNg wcsFluentFrameNg : wcsFluentFrameNgs) {
                                                                            String containerCode = wcsFluentFrameNg.getContainerCode();
                                                                            wcsFluentFrameNgService.delectContainerCode(containerCode);
                                                                        }
                                                                    }
                                                                    String nestingJson = JsonUtil.toJson(materialDaos);
                                                                    WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                                    wcsInboundMission.setIsNest(0);
                                                                    wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                                    //生成入库任务
                                                                    wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                                    wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                                    wcsInboundMission.setContainerCode(palletCode);
                                                                    wcsInboundMission.setSource(inboundStorageCode);
                                                                    wcsInboundMission.setDestination(destinationStorageCode);
                                                                    wcsInboundMission.setContainerType(TaskType.WORKBIN.getStatus());
                                                                    wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                                    wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                                                    wcsInboundMission.setPriority(90);
                                                                    wcsInboundMission.setIsPlc(1);
                                                                    wcsInboundMission.setIsWms(1);
                                                                    StringBuilder sb = new StringBuilder();
                                                                    List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                                                                    for (String materialCode : materialCodeList) {
                                                                        if (sb.length() > 0) {
                                                                            sb.append(",");
                                                                        }
                                                                        sb.append(materialCode);
                                                                    }
                                                                    String materIalCode = sb.toString();
                                                                    wcsInboundMission.setMaterialCode(materIalCode);
                                                                    wcsInboundMission.setFloor(TaskType.TWO_FLOOR.getMessage());
                                                                    wcsInboundMission.setNestingJson(nestingJson);
//                                                                WcsInboundMission wcsInboundMissions = wcsInboundMissionService.selectContainerCodeAndStatus(palletCode,TaskStatus.Task_create.getStatus());
//                                                                if (wcsInboundMissions !=null) {
//
//                                                                }
                                                                    boolean b3 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                                    if (!b3) {
                                                                        fluentFrameLog.error("创建空箱入库任务失败");
                                                                        throw new RuntimeException("创建空箱入库任务失败");
                                                                    }
                                                                    //todo 1
//                                                                boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                                }
                                                            } else {
                                                                fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                                                List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getMessage());
                                                                if (wcsFluentFrameNgs.isEmpty()) {
//                                                            boolean b1 = wcsFluentFrameConfigService.updateWritePlc(id, 1);
                                                                    WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                                                    wcsFluentFrameNg.setNg(MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getMessage());
                                                                    wcsFluentFrameNg.setContainerCode(palletCode);
                                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                                    boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                                                } else {
                                                                    WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                                                    wcsFluentFrameNg.setIp(deviceIp);
                                                                    wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
//                                    else if (mode == 2) {
//                                        //合板操作，直接通知plc往下流
//                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
//                                        fluentFrameLog.info("合箱查询箱号：{}，合箱操作查询到的数据：{}", palletCode, wcsFluentFrameOutboundDetails);
//                                        if (wcsFluentFrameOutboundDetails != null) {
//                                            Integer outboundDetailsId = wcsFluentFrameOutboundDetails.getId();
//                                            if (size != 0) {
//                                                size--;
//                                            }
//                                            fluentFrameLog.info("合箱操作修改流利架数量：{}，{}", id, size);
//                                            //修改数量
//                                            boolean b2 = wcsFluentFrameConfigService.updateSize(id, size);
//                                            //整箱出库，清空流利架上面的容器
//                                            WcsFluentFrameOutboundDetailsHistory wcsFluentFrameOutboundDetailsHistory = new WcsFluentFrameOutboundDetailsHistory();
//                                            BeanUtils.copyProperties(wcsFluentFrameOutboundDetails, wcsFluentFrameOutboundDetailsHistory);
//                                            wcsFluentFrameOutboundDetailsHistory.setId(null);
//                                            wcsFluentFrameOutboundDetailsHistoryService.insertFluentFrameOutboundDetailsHistory(wcsFluentFrameOutboundDetailsHistory);
//                                            //整箱出库删除流利架出库明细
//                                            wcsFluentFrameOutboundDetailsService.deleteId(outboundDetailsId);
//                                            //往流利架地址位写入
//                                            //往流利架地址位写入
////                                                    fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
//                                            fluentFrameLog.info("合箱直接往PLC写整箱出：{}", cylinderControlAddress);
//                                            boolean b1 = fluentFrame.writeWithRetry(cylinderControlAddress, 1, unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
//                                        }
//                                    }
                                    } else {
                                        fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.TWO_SIDES_CODE_MISMATCH.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                        List<WcsFluentFrameNg> wcsFluentFrameNgs = wcsFluentFrameNgService.selectContainerCodeAndNg(palletCode, MaterialStatus.TWO_SIDES_CODE_MISMATCH.getMessage());
                                        if (wcsFluentFrameNgs.isEmpty()) {
                                            WcsFluentFrameNg wcsFluentFrameNg = new WcsFluentFrameNg();
                                            wcsFluentFrameNg.setNg(MaterialStatus.TWO_SIDES_CODE_MISMATCH.getMessage());
                                            wcsFluentFrameNg.setContainerCode(palletCode);
                                            wcsFluentFrameNg.setIp(deviceIp);
                                            fluentFrameLog.info("入库两边读码不一致记录：{}", wcsFluentFrameNg);
                                            boolean b1 = wcsFluentFrameNgService.insertNg(wcsFluentFrameNg);
                                        } else {
                                            WcsFluentFrameNg wcsFluentFrameNg = wcsFluentFrameNgs.get(0);
                                            wcsFluentFrameNg.setIp(deviceIp);
                                            wcsFluentFrameNgService.updateIp(wcsFluentFrameNg);
                                        }
                                    }
                                }else if (wcsFluentFrameOutboundDetails1 !=null &&  (mode == 2)){
                                    //合板操作，直接通知plc往下流
                                    fluentFrameLog.info("合箱查询箱号：{}，合箱操作查询到的数据：{}", palletCode, wcsFluentFrameOutboundDetails1);
                                    Integer outboundDetailsId = wcsFluentFrameOutboundDetails1.getId();
                                    if (size != 0) {
                                        size--;
                                    }
                                    fluentFrameLog.info("合箱操作修改流利架数量：{}，{}", id, size);
                                    //修改数量
                                    boolean b2 = wcsFluentFrameConfigService.updateSize(id, size);
                                    //整箱出库，清空流利架上面的容器
                                    WcsFluentFrameOutboundDetailsHistory wcsFluentFrameOutboundDetailsHistory = new WcsFluentFrameOutboundDetailsHistory();
                                    BeanUtils.copyProperties(wcsFluentFrameOutboundDetails1, wcsFluentFrameOutboundDetailsHistory);
                                    wcsFluentFrameOutboundDetailsHistory.setId(null);
                                    wcsFluentFrameOutboundDetailsHistoryService.insertFluentFrameOutboundDetailsHistory(wcsFluentFrameOutboundDetailsHistory);
                                    //整箱出库删除流利架出库明细
                                    wcsFluentFrameOutboundDetailsService.deleteId(outboundDetailsId);
                                    //往流利架地址位写入
                                    //往流利架地址位写入
//                                                    fluentFrame.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    fluentFrameLog.info("合箱直接往PLC写整箱出：{}", cylinderControlAddress);
                                    boolean b1 = fluentFrame.writeWithRetry(cylinderControlAddress, 1, unitId, MaterialStatus.RETRY_COUNT.getStatus(), region);
                                }
                            }
                        }
                        if (sortingStatus != null && sortingStatus == 0 && writePlc == 1) {
                            boolean b = wcsFluentFrameConfigService.updateWritePlc(id, 0);
                            if (!b) {
                                fluentFrameLog.error("2楼流利架修改写入plc字段失败，数据异常");
                                throw new RuntimeException("2楼流利架修改写入plc字段失败，数据异常");
                            }
                        }
                    }

                    //查询A区域琉璃架数量
                    Integer oneNumberOfLayers = fluentFrame.readHoldingRegisters(region, 17, unitId);
                    //第二个琉璃架上层数量
                    Integer twoNumberOfLayers = fluentFrame.readHoldingRegisters(region, 47, unitId);
                    LocalDateTime ctuTakeTime = wcsFluentFrameConfig.getCtuTakeTime();
                    LocalDateTime now = LocalDateTime.now();
                    long seconds = Duration.between(ctuTakeTime, now).getSeconds();
                    WcsConfiguration WcsConfigurationInbSize = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_INBOUND_SIZE.getMessage());
                    int inbSize = Integer.parseInt(WcsConfigurationInbSize.getConfigValue());
                    WcsConfiguration WcsConfigurationInbTime = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_INBOUND_TIME.getMessage());
                    int inbTime = Integer.parseInt(WcsConfigurationInbTime.getConfigValue());
                    WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_PRE_SCHEDULING_TIME.getMessage());
                    int inbPreSchedulingTime = Integer.parseInt(wcsConfiguration.getConfigValue());

                    //更新时间小于30秒，CTU取货位置有货，直接下发给AGV
                    if (seconds < inbPreSchedulingTime) {
                        Integer inboundThreeAddressStatus = fluentFrame.readHoldingRegisters(region, inboundThreeAddress, unitId);
                        fluentFrameLog.info("更新时间小于30秒最后一段地址位：{},最后一段是否有货：,{}", inboundThreeAddress, inboundThreeAddressStatus);
                        if (Objects.equals(inboundThreeAddressStatus, MaterialStatus.MATERIAL_STATUS_YES.getStatus())) {
                            //有料获取读码结果
                            Integer threeInbReadAddress = wcsFluentFrameConfig.getThreeInbReadAddress();
                            String palletCode = fluentFrame.readHoldingRegistersString(region, threeInbReadAddress, unitId);
                            fluentFrameLog.info("更新时间小于30秒最后一段读码地址位：{},最后一段读码信息：,{}", threeInbReadAddress, palletCode);
                            //下发任务给AGV，修改任务状态
                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(palletCode);
                            if (!wcsInboundMissionList.isEmpty()) {
                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                fluentFrameLog.info("更新时间小于30秒第三段查询到的任务：{}", wcsInboundMission);
                                if (wcsInboundMission.getMissionStatus() == 0) {
                                    String inboundCode = wcsInboundMission.getInboundCode();
                                    Integer priority = wcsInboundMission.getPriority();
                                    agvTaskSend(wcsInboundMission, inboundCode, priority, palletCode, id);
                                }
                            }
                        }
                    } else if (oneNumberOfLayers != null && oneNumberOfLayers + twoNumberOfLayers >= inbSize) {
                        fluentFrameAgvTaskSend(wcsFluentFrameConfig, inbRequestTake, unitId, direction, inboundThreeAddress, threeInbReturnResult, workstation, inboundStorageCode, id, region);
                    } else {
                        if (TaskType.DIRECTION.getMessage().equals(direction)) {
                            //拿到琉璃架左右数量，查询任务创建时间，大于3分钟直接下发
                            LocalDateTime leftTime = null;
                            LocalDateTime rightTime = null;
                            if (oneNumberOfLayers != 0) {
                                switch (oneNumberOfLayers) {
                                    case 1:
                                        Integer readHoldingRegisters = fluentFrame.readHoldingRegisters(region, inboundThreeAddress, unitId);
                                        if (readHoldingRegisters != null && readHoldingRegisters == 1) {
                                            Integer threeInbReadAddress = wcsFluentFrameConfig.getThreeInbReadAddress();
                                            String containerCode = fluentFrame.readHoldingRegistersString10(region, threeInbReadAddress, unitId);
                                            //根据容器编码查询入库任务
                                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                                            if (!wcsInboundMissionList.isEmpty()) {
                                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                leftTime = createTime;
                                            }
                                        }
                                        break;
                                    case 2:
                                        Integer inboundTwoAddressStatus = fluentFrame.readHoldingRegisters(region, inboundTwoAddress, unitId);
                                        if (inboundTwoAddressStatus != null && inboundTwoAddressStatus == 1) {
                                            Integer twoInbReadAddress = wcsFluentFrameConfig.getTwoInbReadAddress();
                                            String containerCode = fluentFrame.readHoldingRegistersString10(region, twoInbReadAddress, unitId);
                                            //根据容器编码查询入库任务
                                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                                            if (!wcsInboundMissionList.isEmpty()) {
                                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                leftTime = createTime;
                                            }
                                        }
                                        break;
                                    case 3:
                                        Integer inboundOneAddressStatus = fluentFrame.readHoldingRegisters(region, inboundOneAddress, unitId);
                                        if (inboundOneAddressStatus != null && inboundOneAddressStatus == 1) {
                                            Integer oneInbReadAddress = wcsFluentFrameConfig.getOneInbReadAddress();
                                            String containerCode = fluentFrame.readHoldingRegistersString10(region, oneInbReadAddress, unitId);
                                            //根据容器编码查询入库任务
                                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                                            if (!wcsInboundMissionList.isEmpty()) {
                                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                leftTime = createTime;
                                            }
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            if (twoNumberOfLayers != 0) {
                                //查询右边琉璃架
                                WcsFluentFrameConfig wcsFluentFrameConfigRight = wcsFluentFrameConfigService.selectWorkstationAndDirection(workstation, TaskType.DIRECTION_RIGHT.getMessage());
                                if (wcsFluentFrameConfigRight != null) {
                                    Integer inboundThreeAddressRight = wcsFluentFrameConfigRight.getInboundThreeAddress();
                                    Integer inboundTwoAddressRight = wcsFluentFrameConfigRight.getInboundTwoAddress();
                                    Integer inboundOneAddressRight = wcsFluentFrameConfigRight.getInboundOneAddress();
                                    switch (twoNumberOfLayers) {
                                        case 1:
                                            Integer inboundThreeAddressRightStatus = fluentFrame.readHoldingRegisters(region, inboundThreeAddressRight, unitId);
                                            if (inboundThreeAddressRightStatus != null && inboundThreeAddressRightStatus == 1) {
                                                Integer threeInbReadAddressRight = wcsFluentFrameConfigRight.getThreeInbReadAddress();
                                                String containerCode = fluentFrame.readHoldingRegistersString10(region, threeInbReadAddressRight, unitId);
                                                //根据容器编码查询入库任务
                                                List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                                                if (!wcsInboundMissionList.isEmpty()) {
                                                    WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                    LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                    rightTime = createTime;
                                                }
                                            }
                                            break;
                                        case 2:
                                            Integer inboundTwoAddressRightStatus = fluentFrame.readHoldingRegisters(region, inboundTwoAddressRight, unitId);
                                            if (inboundTwoAddressRightStatus != null && inboundTwoAddressRightStatus == 1) {
                                                Integer twoInbReadAddressRight = wcsFluentFrameConfigRight.getTwoInbReadAddress();
                                                String containerCode = fluentFrame.readHoldingRegistersString10(region, twoInbReadAddressRight, unitId);
                                                //根据容器编码查询入库任务
                                                List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                                                if (!wcsInboundMissionList.isEmpty()) {
                                                    WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                    LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                    rightTime = createTime;
                                                }
                                            }
                                            break;
                                        case 3:
                                            Integer inboundOneAddressRightStatus = fluentFrame.readHoldingRegisters(region, inboundOneAddressRight, unitId);
                                            if (inboundOneAddressRightStatus != null && inboundOneAddressRightStatus == 1) {
                                                Integer oneInbReadAddressRight = wcsFluentFrameConfigRight.getOneInbReadAddress();
                                                String containerCode = fluentFrame.readHoldingRegistersString10(region, oneInbReadAddressRight, unitId);
                                                //根据容器编码查询入库任务
                                                List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                                                if (!wcsInboundMissionList.isEmpty()) {
                                                    WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                    LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                    rightTime = createTime;
                                                }
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            if (leftTime != null && rightTime != null) {
                                LocalDateTime latest = leftTime.isAfter(rightTime) ? leftTime : rightTime;
                                fluentFrameLog.info("最新的时间是：{}", latest);
                                LocalDateTime now1 = LocalDateTime.now();
                                long seconds1 = Duration.between(latest, now1).getSeconds();
                                if (seconds1 > inbTime) {
                                    //最新时间大于三分钟后，下发左边任务再下发右边任务
                                    fluentFrameAgvTaskSend(wcsFluentFrameConfig, inbRequestTake, unitId, direction, inboundThreeAddress, threeInbReturnResult, workstation, inboundStorageCode, id, region);
                                }
                            } else if (leftTime != null) {
                                LocalDateTime leftTimeNow = LocalDateTime.now();
                                long seconds1 = Duration.between(leftTime, leftTimeNow).getSeconds();
                                if (seconds1 > inbTime) {
                                    //预调度
                                    Integer inbRequestTaskStatus = fluentFrame.readHoldingRegisters(region, inbRequestTake, unitId);
                                    Integer inboundThreeAddressStatus = fluentFrame.readHoldingRegisters(region, inboundThreeAddress, unitId);
                                    fluentFrameLog.info("最后一段地址位：{},最后一段是否有货：,{}", inboundThreeAddress, inboundThreeAddressStatus);
                                    if (Objects.equals(inboundThreeAddressStatus, MaterialStatus.MATERIAL_STATUS_YES.getStatus()) && inbRequestTaskStatus != null && inbRequestTaskStatus == 1 && inbPlcStatus == 0) {
                                        //有料获取读码结果
                                        Integer threeInbReadAddress = wcsFluentFrameConfig.getThreeInbReadAddress();
                                        String palletCode = fluentFrame.readHoldingRegistersString(region, threeInbReadAddress, unitId);
                                        fluentFrameLog.info("最后一段读码地址位：{},最后一段读码信息：,{}", threeInbReadAddress, palletCode);
                                        //下发任务给AGV，修改任务状态
                                        List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(palletCode);
                                        if (!wcsInboundMissionList.isEmpty()) {
                                            WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                            fluentFrameLog.info("第三段查询到的任务：{}", wcsInboundMission);
                                            if (wcsInboundMission.getMissionStatus() == 0) {
                                                //下发预调度
                                                TaskPretaskDto taskPretaskDto = new TaskPretaskDto();
                                                taskPretaskDto.setSiteCode(inboundStorageCode);
//                                                WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_PRE_SCHEDULING_TIME.getMessage());
                                                String configValue = wcsConfiguration.getConfigValue();
                                                taskPretaskDto.setNextTaskTime(configValue);
                                                taskPretaskDto.setRobotType(String.valueOf(TaskType.TWO_FLOOR_ROBOT_TYPE.getStatus()));
                                                AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskPretask(taskPretaskDto);
                                                String inboundCode = wcsInboundMission.getInboundCode();
                                                agvTaskSend(wcsInboundMission, inboundCode, PriorityEnum.FOUR.getWeight(), palletCode, id);
                                            }
                                        }
                                    }
                                }
                            } else if (rightTime != null) {
                                LocalDateTime rightTimeNow = LocalDateTime.now();
                                long seconds1 = Duration.between(rightTime, rightTimeNow).getSeconds();
                                if (seconds1 > inbTime) {
                                    fluentFrameLog.info("右边琉璃架任务大于180任务呢时间{},当前时间{}", rightTime, rightTimeNow);
                                    //查询右边琉璃架第一段下发任务
                                    WcsFluentFrameConfig wcsFluentFrameConfigRight = wcsFluentFrameConfigService.selectWorkstationAndDirection(workstation, TaskType.DIRECTION_RIGHT.getMessage());
                                    if (wcsFluentFrameConfigRight != null) {
                                        Integer inboundThreeAddressRight = wcsFluentFrameConfigRight.getInboundThreeAddress();
                                        Integer inbRequestTakeRight = wcsFluentFrameConfigRight.getInbRequestTake();
                                        Integer unitIdRight = wcsFluentFrameConfigRight.getUnitId();
                                        String inboundStorageCodeRight = wcsFluentFrameConfigRight.getInboundStorageCode();
                                        Integer idRight = wcsFluentFrameConfigRight.getId();
                                        Integer inboundThreeAddressRightStatus = fluentFrame.readHoldingRegisters(region, inboundThreeAddressRight, unitId);
                                        fluentFrameLog.info("右边琉璃架最后一段地址位：{},右边琉璃架最后一段是否有货：{}", inboundThreeAddress, inboundThreeAddressRightStatus);
                                        Integer readHoldingRegisters = fluentFrame.readHoldingRegisters(region, inbRequestTakeRight, unitIdRight);
                                        if (Objects.equals(inboundThreeAddressRightStatus, MaterialStatus.MATERIAL_STATUS_YES.getStatus()) && readHoldingRegisters != null && readHoldingRegisters == 1) {
                                            //有料获取读码结果
                                            Integer threeInbReadAddressRight = wcsFluentFrameConfigRight.getThreeInbReadAddress();
                                            String palletCode = fluentFrame.readHoldingRegistersString(region, threeInbReadAddressRight, unitId);
                                            fluentFrameLog.info("右边琉璃架最后一段读码地址位：{},右边琉璃架最后一段读码信息：,{}", threeInbReadAddressRight, palletCode);
                                            //下发任务给AGV，修改任务状态
                                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(palletCode);
                                            if (!wcsInboundMissionList.isEmpty()) {
                                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                                fluentFrameLog.info("右边琉璃架第三段查询到的任务：{}", wcsInboundMission);
                                                if (wcsInboundMission.getMissionStatus() == 0) {
                                                    //下发预调度
                                                    TaskPretaskDto taskPretaskDto = new TaskPretaskDto();
                                                    taskPretaskDto.setSiteCode(inboundStorageCodeRight);
//                                                    WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_PRE_SCHEDULING_TIME.getMessage());
                                                    String configValue = wcsConfiguration.getConfigValue();
                                                    taskPretaskDto.setNextTaskTime(configValue);
                                                    taskPretaskDto.setRobotType(String.valueOf(TaskType.TWO_FLOOR_ROBOT_TYPE.getStatus()));
                                                    AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskPretask(taskPretaskDto);
                                                    String inboundCode = wcsInboundMission.getInboundCode();
                                                    agvTaskSend(wcsInboundMission, inboundCode, PriorityEnum.FOUR.getWeight(), palletCode, idRight);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void agvTaskSend(WcsInboundMission wcsInboundMission, String inboundCode, Integer priority, String palletCode, Integer id) {
        AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
        agvTaskSubmitDto.setTaskType("AAAAAA");
        ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
        TargetRoute targetRoute = new TargetRoute();
        TargetRoute targetRoutes = new TargetRoute();
        //添加起点
        targetRoute.setSeq(0);
        targetRoute.setType(TaskType.STORAGE.getMessage());
        targetRoute.setCode(wcsInboundMission.getSource());
        //添加终点
        targetRoutes.setSeq(1);
        targetRoutes.setType(TaskType.STORAGE.getMessage());
        targetRoutes.setCode(wcsInboundMission.getDestination());
        targetRouteList.add(targetRoute);
        targetRouteList.add(targetRoutes);
        agvTaskSubmitDto.setTargetRoute(targetRouteList);
        agvTaskSubmitDto.setRobotTaskCode(inboundCode);
        agvTaskSubmitDto.setInitPriority(priority);

        CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
        carrierInfoDto.setCarrierCode(palletCode);
        carrierInfoDto.setCarrierType(TaskType.TWO_Task_assignment_Container_binding.getMessage());
        ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
        carrierInfoDtos.add(carrierInfoDto);
        ExtraDto extraDto = new ExtraDto();
        extraDto.setCarrierInfo(carrierInfoDtos);
        agvTaskSubmitDto.setExtra(extraDto);
        String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
        if (taskCode != null) {
            WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
            wcsAgvReleaseGoods.setTaskCode(inboundCode);
            wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
            wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
            wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_PICK_UP.getStatus());
            wcsAgvReleaseGoods.setFloor(TaskType.TWO_FLOOR.getStatus());
            boolean b3 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
            if (!b3) {
                fluentFrameLog.error("创建agv放货表失败");
                throw new RuntimeException("创建agv放货表失败");
            }
            boolean b1 = wcsInboundMissionService.updateMissionStatus(wcsInboundMission.getInboundCode(), TaskStatus.task_send.getStatus());
            if (!b1) {
                fluentFrameLog.error("数据回滚，流利架下发agv任务，修改数据库失败");
                throw new RuntimeException("数据回滚，流利架下发agv任务，修改数据库失败");
            }
            //修改琉璃架入库PLC状态
            boolean b = wcsFluentFrameConfigService.updateInbPlcStatus(id, 1);
        }
    }

    private void fluentFrameAgvTaskSend(WcsFluentFrameConfig wcsFluentFrameConfig, Integer inbRequestTake, Integer unitId, String direction, Integer inboundThreeAddress, Integer threeReturnResult, String workstation, String inboundStorageCode, Integer id, String region) {
        if (TaskType.DIRECTION.getMessage().equals(direction)) {
            Integer inbRequestTaskStatus = fluentFrame.readHoldingRegisters(region, inbRequestTake, unitId);
            Integer inboundThreeAddressStatus = fluentFrame.readHoldingRegisters(region, inboundThreeAddress, unitId);
            fluentFrameLog.info("最后一段是否有货地址位：{},最后一段是否有货：,{}", inboundThreeAddress, inboundThreeAddressStatus);
            if (Objects.equals(inboundThreeAddressStatus, MaterialStatus.MATERIAL_STATUS_YES.getStatus()) && inbRequestTaskStatus != null && inbRequestTaskStatus == 1) {
                //有料获取读码结果
                Integer threeInbReadAddress = wcsFluentFrameConfig.getThreeInbReadAddress();
                String containerCode = fluentFrame.readHoldingRegistersString10(region, threeInbReadAddress, unitId);
                fluentFrameLog.info("最后一段读码地址位：{},最后一段读码信息：,{}", threeInbReadAddress, containerCode);
                //下发任务给AGV，修改任务状态
                List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
                if (!wcsInboundMissionList.isEmpty()) {
                    WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                    fluentFrameLog.info("第三段查询到的任务：{}", wcsInboundMission);
                    if (wcsInboundMission.getMissionStatus() == 0) {
                        //下发预调度
                        TaskPretaskDto taskPretaskDto = new TaskPretaskDto();
                        taskPretaskDto.setSiteCode(inboundStorageCode);
                        WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_PRE_SCHEDULING_TIME.getMessage());
                        String configValue = wcsConfiguration.getConfigValue();
//                        taskPretaskDto.setNextTaskTime("999");
                        taskPretaskDto.setNextTaskTime(configValue);
                        taskPretaskDto.setRobotType(String.valueOf(TaskType.TWO_FLOOR_ROBOT_TYPE.getStatus()));
                        AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskPretask(taskPretaskDto);
                        String inboundCode = wcsInboundMission.getInboundCode();
                        agvTaskSend(wcsInboundMission, inboundCode, PriorityEnum.FOUR.getWeight(), containerCode, id);
                    }
                }
            }
            //查询右边琉璃架第一段下发任务
            WcsFluentFrameConfig wcsFluentFrameConfigRight = wcsFluentFrameConfigService.selectWorkstationAndDirection(workstation, TaskType.DIRECTION_RIGHT.getMessage());
            if (wcsFluentFrameConfigRight != null) {
                Integer inboundThreeAddressRight = wcsFluentFrameConfigRight.getInboundThreeAddress();
                Integer inbRequestTakeRight = wcsFluentFrameConfigRight.getInbRequestTake();
                Integer unitIdRight = wcsFluentFrameConfigRight.getUnitId();
                Integer rightId = wcsFluentFrameConfigRight.getId();
                Integer inboundThreeAddressRightStatus = fluentFrame.readHoldingRegisters(region, inboundThreeAddressRight, unitId);
                fluentFrameLog.info("右边琉璃架最后一段地址位：{},右边琉璃架最后一段是否有货：,{}", inboundThreeAddress, inboundThreeAddressRightStatus);
                Integer readHoldingRegisters = fluentFrame.readHoldingRegisters(region, inbRequestTakeRight, unitIdRight);
                if (Objects.equals(inboundThreeAddressRightStatus, MaterialStatus.MATERIAL_STATUS_YES.getStatus()) && readHoldingRegisters != null && readHoldingRegisters == 1) {
                    //有料获取读码结果
                    Integer threeInbReadAddressRight = wcsFluentFrameConfigRight.getThreeInbReadAddress();
                    String palletCode = fluentFrame.readHoldingRegistersString(region, threeInbReadAddressRight, unitId);
                    fluentFrameLog.info("右边琉璃架最后一段读码地址位：{},右边琉璃架最后一段读码信息：,{}", threeInbReadAddressRight, palletCode);
                    //下发任务给AGV，修改任务状态
                    List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(palletCode);
                    if (!wcsInboundMissionList.isEmpty()) {
                        WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                        fluentFrameLog.info("右边琉璃架第三段查询到的任务：{}", wcsInboundMission);
                        if (wcsInboundMission.getMissionStatus() == 0) {
                            String source = wcsInboundMission.getSource();
                            String destination = wcsInboundMission.getDestination();
//                            //下发预调度
                            TaskPretaskDto taskPretaskDto = new TaskPretaskDto();
                            taskPretaskDto.setSiteCode(source);
                            WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.TWO_FLOOR_PRE_SCHEDULING_TIME.getMessage());
                            String configValue = wcsConfiguration.getConfigValue();
                            taskPretaskDto.setNextTaskTime("999");
                            taskPretaskDto.setRobotType(String.valueOf(TaskType.TWO_FLOOR_ROBOT_TYPE.getStatus()));
                            AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskPretask(taskPretaskDto);

                            String inboundCode = wcsInboundMission.getInboundCode();
                            AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                            //todo 任务类型，根据现场情况来定
                            agvTaskSubmitDto.setTaskType("AAAAAA");
                            ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                            TargetRoute targetRoute = new TargetRoute();
                            TargetRoute targetRoutes = new TargetRoute();
                            //添加起点
                            targetRoute.setSeq(0);
                            targetRoute.setType(TaskType.STORAGE.getMessage());
                            targetRoute.setCode(wcsInboundMission.getSource());
                            //添加终点
                            targetRoutes.setSeq(1);
                            targetRoutes.setType(TaskType.STORAGE.getMessage());
                            targetRoutes.setCode(destination);
                            targetRouteList.add(targetRoute);
                            targetRouteList.add(targetRoutes);
                            agvTaskSubmitDto.setTargetRoute(targetRouteList);
                            agvTaskSubmitDto.setRobotTaskCode(inboundCode);
                            agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());

                            CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
                            carrierInfoDto.setCarrierCode(palletCode);
                            carrierInfoDto.setCarrierType(TaskType.TWO_Task_assignment_Container_binding.getMessage());
                            ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
                            carrierInfoDtos.add(carrierInfoDto);
                            ExtraDto extraDto = new ExtraDto();
                            extraDto.setCarrierInfo(carrierInfoDtos);
                            agvTaskSubmitDto.setExtra(extraDto);
                            String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                            if (taskCode != null) {
                                WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
                                wcsAgvReleaseGoods.setTaskCode(inboundCode);
                                wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
                                wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
                                wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_PICK_UP.getStatus());
                                wcsAgvReleaseGoods.setFloor(TaskType.TWO_FLOOR.getStatus());
                                boolean b3 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
                                if (!b3) {
                                    fluentFrameLog.error("创建agv放货表失败");
                                    throw new RuntimeException("创建agv放货表失败");
                                }
                                boolean b1 = wcsInboundMissionService.updateMissionStatus(wcsInboundMission.getInboundCode(), TaskStatus.task_send.getStatus());
                                //修改琉璃架入库PLC状态
                                boolean b = wcsFluentFrameConfigService.updateInbPlcStatus(rightId, 1);
                                if (!b1) {
                                    fluentFrameLog.error("数据回滚，流利架下发agv任务，修改数据库失败");
                                    throw new RuntimeException("数据回滚，流利架下发agv任务，修改数据库失败");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

